package com.hongdee.scm.carInvoicePrice.service.impl;

import com.hongdee.common.util.TokenUtil;
import com.hongdee.scm.carInvoicePrice.dao.ITScmCarInvoicePriceDao;
import com.hongdee.scm.carInvoicePrice.entity.TScmCarInvoicePrice;
import com.hongdee.scm.carInvoicePrice.service.ITScmCarInvoicePriceService;
import com.hongdee.scm.common.service.ICommonService;
import com.hongdee.scm.common.service.impl.Common;
import com.hongdee.scm.monthlybalance.service.ITScmMonthlyBalanceService;
import com.hongdee.scm.util.SerialNumFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;


/**
 * Created by Mr. Xu on 2017/5/4.
 */
@Service
public class TScmCarInvoicePriceServiceImpl implements ITScmCarInvoicePriceService {
    @Autowired
    private ITScmCarInvoicePriceDao invoicePriceDao;
    @Autowired
    private ICommonService com;
    @Autowired
    private ITScmMonthlyBalanceService itScmMonthlyBalanceService;
    //价格单据表
    private String tabName = "t_scm_invoice_price";
    private String tabName1 = "T_Scm_Sale_Order";
    private String tabName2 = "T_Scm_Car";


    /**
     * 打印单据调用价格单据查询
     *
     * @param carId
     * @param invoicesType
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public Map selectByinvoice(String carId, String invoicesType, String uid, String invoicesPrice)
            throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d = new Date();
        String data = sdf.format(d);
        String cid= TokenUtil.getCompanyId(uid);
        if(this.itScmMonthlyBalanceService.ifMonthlyBalance(cid,new Date())){
            throw new Exception("该月已月结或月结中!");
        }
        Map<String, Object> map = new HashMap();
        List params = new ArrayList();
        String sql = "select * from " + tabName + " p where  p.car_id= ? and p.invoices_type = ? and p.invoices_price = ? order by strat_printTime desc";
        params.add(carId);
        params.add(invoicesType);
        params.add(invoicesPrice);
        //根据车辆id 类型 价格 查询打印记录
        Map ma = this.invoicePriceDao.info(sql, params.toArray());
        String conncetionNo = "";
        String getStrat_printTime = "";
        if (ma.size() > 0) {
            if (ma.get("conncetionNo") != null && !StringUtils.isEmpty(ma.get("conncetionNo"))) {
                //获取流水号和打印最初时间
                conncetionNo = String.valueOf(ma.get("conncetionNo"));
            }
            if (ma.get("stratPrintTime") != null && !StringUtils.isEmpty(ma.get("stratPrintTime"))) {
                //获取流水号和打印最初时间
                getStrat_printTime = String.valueOf(ma.get("stratPrintTime"));
            }
            map.put("id",ma.get("id"));
            map.put("conncetionNo", conncetionNo);
            map.put("getStrat_printTime", getStrat_printTime);
        } else {
            TScmCarInvoicePrice price = new TScmCarInvoicePrice();
            price.setCreateUser(uid);
            price.setCreateTime(Calendar.getInstance().getTimeInMillis());
            price.setInvoicesPrice(invoicesPrice);
            price.setInvoicesType(invoicesType);
            price.setCarId(carId);
            price.setConncetionNo(SerialNumFactory.generateSerialNum(uid, invoicesType));
            price.setStrat_printTime(Calendar.getInstance().getTime());
            price.setPrintCount("1");
            this.invoicePriceDao.saveOrUpdate(price);
            map.put("conncetionNo", price.getConncetionNo());
            map.put("getStrat_printTime", data);
            map.put("id",price.getId());
        }
            return map;
    }




    /**
     * 打印完成更新时间和次数
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public void updateByinvoice(String id) throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
        Date d = new Date();
        String date = sdf.format(d);
        String sql ="update "+tabName+" t set t.Print_count = t.Print_count+1,t.end_printTime = ? where id=?";
        List list =  new ArrayList();
        list.add(date);
        list.add(id);
        this.invoicePriceDao.executeSQL(sql,list.toArray());

    }

    /**
     * 打印成本计价单
     *
     * @param
     * @return
     * @throws Exception
     */
    @Override
    public void saveCarInvoicePrice(TScmCarInvoicePrice invoicePrice) throws Exception{
            this.invoicePriceDao.saveOrUpdate(invoicePrice);
    }

    /**
     * 打印入库单修改状态
     * @param
     * @return
     * @throws Exception
     */
    @Override
    public void updateByinvoiceType(String invoicesType,String carId) throws Exception{
        List params = new ArrayList();
        if(invoicesType.equals("3")){
            System.out.print(carId);
            String sql ="update "+tabName2+" t set t.finance_type = '3' where  id=?";
            params.add(carId);
            this.invoicePriceDao.executeSQL(sql,params.toArray());
        }
    }

    /**
     * 车辆价格历史明细
     * @param carId
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public Map getHistoryPrice(String carId,String uid,String start,String limit) throws Exception{

        Common common = new Common();
        Boolean hasWhere = false;
        List params = new ArrayList();
        StringBuffer sql = new StringBuffer();
        sql.append("select SUBSTR(p.strat_printTime,1,10) date,p.invoices_price,invoices_type")
           .append(" from t_scm_invoice_price p left join t_scm_car c on c.id = p.car_id ");

        //公司
        String cid = TokenUtil.getCompanyId(uid);
        if(!cid.isEmpty()){
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append(" c.company_id = ? ");
            params.add(cid);
        }
        //车辆id
        if(carId!=null&&!StringUtils.isEmpty(carId)){
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append(" p.car_id= ?");
            params.add(carId);
        }else{
            throw new Exception("请选择车辆");
        }
        sql.append(" order by p.strat_printTime desc");

        return this.invoicePriceDao.page(sql.toString(),params.toArray(),start, limit);

    }

    /**
     * 维护已入库车辆的暂估价格
     * @param carId
     * @param invoicesType
     * @param uid
     * @param invoicesPrice
     * @throws Exception
     */
    @Override
    public void updateEstimatePrice(String carId,String invoicesType,String uid,String invoicesPrice) throws Exception{

        if(this.invoicePriceDao.info("select * from t_scm_car where id = ? and finance_type='3'",carId).size()>0){
            throw new Exception("该车已正式入库不能修改暂估价格!");
        }

        if(this.invoicePriceDao.info("select * from t_scm_sale_order_detail where car_id=? and status='1' ",carId).size()>0){
            throw new Exception("该车已售不能修改暂估价格!");
        }
        List params = new ArrayList();
        String sql = "select * from " + tabName + " p where  p.car_id= ? and p.invoices_type = ? order by strat_printTime desc";
        params.add(carId);
        params.add(invoicesType);
        //params.add(invoicesPrice);
        //根据车辆id 类型 价格 查询打印记录
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
        Map ma = this.invoicePriceDao.info(sql, params.toArray());
        if (ma.size() > 0) {
            this.invoicePriceDao.executeSQL("update t_scm_invoice_price set invoices_price=? where id=?",invoicesPrice,ma.get("id"));

        } else {
            String vin = this.invoicePriceDao.info("select * from t_scm_car where id = ?",carId).get("vin").toString();
            throw new Exception("请先入库vin为"+vin+"的车辆");
        }
        //更新车辆表里的暂估价格
        this.invoicePriceDao.executeSQL("update t_scm_car set estimate_price= ? where id = ?",invoicesPrice,carId);
        //更新T_Scm_Car_Price_Detail表车辆暂估
        this.invoicePriceDao.executeSQL("update T_Scm_Car_Price_Detail set estimate_price = ? " +
                " where vin in (select vin from T_Scm_Car where id = ? )",invoicesPrice,carId);

    }

    @Override
    public Map batchByinvoice(List<String> carId,String invoicesType,String uid,String invoicesPrice,boolean flag) throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d = new Date();
        String data = sdf.format(d);
        String cid = TokenUtil.getCompanyId(uid);
        if(this.itScmMonthlyBalanceService.ifMonthlyBalance(cid,new Date())){
            throw new Exception("该月已月结或月结中,不能车辆入库!");
        }

        Map<String, Object> map = new HashMap();
        List<String> ids = new ArrayList<>();
        String conNo ="";
        Date time = new Date();
        if(flag){//正常
            //流水号
            conNo = SerialNumFactory.generateSerialNum(uid, invoicesType);
            //日期
            time = Calendar.getInstance().getTime();
        }else{//入到上个月最后一天
            //流水号
            conNo = this.getConnectNo(uid);
            //日期
            time = new SimpleDateFormat("yyyy-MM-dd").parse(this.getLastMaxMonthDate());
        }

        for(String id:carId){
            List params = new ArrayList();
            String sql = "select * from " + tabName + " p where  p.car_id= ? and p.invoices_type = ? and p.invoices_price = ? order by strat_printTime desc";
            params.add(id);
            params.add(invoicesType);
            params.add(invoicesPrice);
            //根据车辆id 类型 价格 查询打印记录
            Map ma = this.invoicePriceDao.info(sql, params.toArray());
            String conncetionNo = "";
            String getStrat_printTime = "";
            if (ma.size() > 0) {
                if (ma.get("conncetionNo") != null && !StringUtils.isEmpty(ma.get("conncetionNo"))) {
                    //获取流水号和打印最初时间
                    conncetionNo = String.valueOf(ma.get("conncetionNo"));
                }
                if (ma.get("stratPrintTime") != null && !StringUtils.isEmpty(ma.get("stratPrintTime"))) {
                    //获取流水号和打印最初时间
                    getStrat_printTime = String.valueOf(ma.get("stratPrintTime"));
                }
                map.put("id",ma.get("id"));
                map.put("conncetionNo", conncetionNo);
                map.put("getStrat_printTime", getStrat_printTime);
            } else {

                TScmCarInvoicePrice price = new TScmCarInvoicePrice();
                price.setCreateUser(uid);
                price.setCreateTime(Calendar.getInstance().getTimeInMillis());
                price.setInvoicesPrice(invoicesPrice);
                price.setInvoicesType(invoicesType);
                price.setCarId(id);
                price.setConncetionNo(conNo);
                price.setStrat_printTime(time);
                price.setPrintCount("1");
                this.invoicePriceDao.saveOrUpdate(price);
                ids.add(price.getId());

            }
            map.put("conncetionNo", conNo);
            map.put("getStrat_printTime", data);
            map.put("id",ids);
        }
        return map;
    }

    /**
     * 获取上个月最后一天
     * @return
     */
    private String getLastMaxMonthDate() {
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH, -1);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        return dft.format(calendar.getTime());
    }

    /**
     * 获取流水号
     * @param uid
     * @return
     * @throws Exception
     */
    private String getConnectNo(String uid) throws Exception{

        //上个月最后一天
        String time = getLastMaxMonthDate();
        String cid = TokenUtil.getCompanyId(uid);
        String conno="";
        List list = this.invoicePriceDao.list("select * from t_scm_invoice_price where car_id in (" +
                " select id from t_scm_car where company_id =? ) and strat_printTime = ? order by conncetion_no desc limit 1",cid,time);
        if(list.size()>0){//存在
            Map map = (Map)list.get(0);
            if(map.get("conncetionNo")!=null&&!"".equals(map.get("conncetionNo"))){ //有流水号
                conno = (Long.parseLong(map.get("conncetionNo").toString())+1)+"";
            }else{//没有流水号
                conno = time.substring(0,4)+time.substring(5,7)+time.substring(8,10)+"001";
            }

        }else{//不存在
            conno = time.substring(0,4)+time.substring(5,7)+time.substring(8,10)+"001";
        }
        return conno;
    }

}


